package at.fhj.antesk.steamvaluecalc.implementations;

import java.util.ArrayList;
import java.util.List;

import at.fhj.antesk.steamvaluecalc.data.Game;
import at.fhj.antesk.steamvaluecalc.data.Price;
import at.fhj.antesk.steamvaluecalc.enums.Currency;
import at.fhj.antesk.steamvaluecalc.exceptions.DataCalculatorException;
import at.fhj.antesk.steamvaluecalc.interfaces.DataCalculator;


public class DataCalculatorImpl implements DataCalculator {

    public double calculateTotalPrice(List<Game> gameList, Currency currency) {
        double result = 0.0;

        for (Game game : gameList) {

            List<Price> prices = game.getPrices();
            for (Price price : prices) {
                Currency currentCurrency = price.getCurrency();
                if (currentCurrency.equals(currency)) {
                    result += price.getAmount();
                    break;
                }
            }

        }

        return result;
    }

    public double calculateTotalHours(List<Game> gameList) {
        double result = 0.0;

        for (Game game : gameList) {
            result += game.getHoursOnRecord();
        }

        return result;
    }

    public void calculateAndSetHourValueForGame(Game game, Currency currency) throws DataCalculatorException {
        List<Price> prices = game.getPrices();
        Price useablePrice = null;
        for (Price price : prices) {
            Currency currentCurrency = price.getCurrency();
            if (currentCurrency.equals(currency)) {
                useablePrice = price;
                break;
            }
        }

        if (useablePrice == null) {
            throw new DataCalculatorException("Price with currency " + currency + " does not exist for game " + game);
        }

        Double amount = useablePrice.getAmount();
        Double hoursOnRecord = game.getHoursOnRecord();
        Double hourValue = round(amount / hoursOnRecord, 2);

        Price result = new Price();
        result.setAmount(hourValue);
        result.setCurrency(currency);

        if (game.getHourValues() == null) {
            List<Price> hourValueList = new ArrayList<Price>();
            hourValueList.add(result);
            game.setHourValues(hourValueList);
        } else {
            game.getHourValues().add(result);
        }
    }

    private double round(double value, int places) {
        if (places < 0)
            throw new IllegalArgumentException();

        long factor = (long)Math.pow(10, places);
        value = value * factor;
        long tmp = Math.round(value);
        return (double)tmp / factor;
    }


}
